<template>
  <div>
    <div class="init-db-container">
      <el-divider content-position="left"><i class="el-icon-folder-opened"></i> 数据导入</el-divider>
      <el-upload
        drag
        accept=".xls,.xlsx"
        :auto-upload="false"
        action="#"
        :limit="1"
        :on-exceed="handleExceed"
        :on-change="importExcel"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em> <br>只支持xls、xlsx后缀的excel文件</div>
      </el-upload>
      <div class="file-path-container">
        <p style="margin:0">上次导入的文件：</p>
        <el-link type="success" style="font-size: 16px">{{lastPath}}</el-link>
      </div>
      <el-button :loading="loading" type="primary" @click="handleImportDB" style="margin-top: 5px"
                 icon="el-icon-upload2">导入数据库
      </el-button>
      <el-button :loading="clearDBLoading" type="warning" @click="handleClearDB" style="margin-top: 5px"
                 icon="el-icon-delete">清除数据库
      </el-button>
    </div>
    <div>
      <el-divider content-position="left"><i class="el-icon-lock"></i> 修改密码</el-divider>
      <div class="change-container">
        <el-input clearable show-password v-model.trim="oldPassword" placeholder="原密码"></el-input>
        <el-input clearable show-password v-model.trim="firstPassword" placeholder="新密码"></el-input>
        <el-input clearable show-password v-model.trim="secondPassword" placeholder="请再输入一次"></el-input>
        <div class="submit-container">
          <el-button type="primary" style="width: 50%" @click="handleChangePassword" icon="el-icon-edit">修改</el-button>
          <el-button type="primary" style="width: 50%" @click="handleResetInput" icon="el-icon-delete">清空</el-button>
        </div>
      </div>
    </div>
    <div>
      <el-divider content-position="left"><i class="el-icon-milk-tea"></i> Bug反馈</el-divider>
      <el-button type="primary" style="width: 25%" @click="handleBugReport" icon="el-icon-message">Bug反馈</el-button>
    </div>
    <!--    <el-dialog-->
    <!--        title="文件读取中，请稍后"-->
    <!--        :visible="centerDialogVisible"-->
    <!--        width="30%"-->
    <!--        center>-->
    <!--        <span>需要注意的是内容是默认不居中的</span>-->
    <!--        <span slot="footer" class="dialog-footer">-->
    <!--  </span>-->
    <!--    </el-dialog>-->
  </div>
</template>

<script>
    import XLSX from 'xlsx'
    import { addItems, clearItems, getData, getDBPath, setData } from '../datastore'

    export default {
        name: 'SysConfig',
        data () {
            return {
                clearDBLoading: false,
                bugMessage: '',
                bugMessagePool: ['海海爱你哟', '胖胖爱你哟', '豆豆爱你哟', '米米爱你哟'],
                positionPool: ['top-right', 'top-left', 'bottom-right', 'bottom-left'],
                typePool: ['success', 'warning', 'info', 'error'],
                dbPath: '',
                lastPath: '',
                oldPassword: '',
                firstPassword: '',
                secondPassword: '',
                loading: false,
                excelData: {
                    header: null,
                    results: null
                },
                fileList: [],
                staff_list: []
            }
        },
        methods: {
            resetData () {
                this.excelData.header = null
                this.excelData.results = null
            },
            readerData (rawFile) {
                return new Promise((resolve, reject) => {
                    const reader = new FileReader()
                    reader.onload = e => {
                        try {
                            const data = e.target.result
                            const workbook = XLSX.read(data, { type: 'array' })
                            const firstSheetName = workbook.SheetNames[0]
                            const worksheet = workbook.Sheets[firstSheetName]
                            // console.log(worksheet)
                            let rangeStringArray = []
                            try {
                                rangeStringArray = this.getRangeStringArray(worksheet)
                            } catch (e) {
                                // eslint-disable-next-line prefer-promise-reject-errors
                                return reject('解析excel文件出错，请核查excel内容的格式')
                            }
                            // console.log(rangeStringArray)
                            let mergeArray = worksheet['!merges']
                            let mergeStringArray = []
                            mergeArray.map(merge => {
                                mergeStringArray.push(XLSX.utils.encode_range(merge))
                            })
                            // console.log(mergeStringArray)
                            let newTypeName = []
                            mergeStringArray.map(merge => {
                                let typeName = XLSX.utils.sheet_to_json(worksheet, {
                                    range: merge,
                                    header: 1,
                                    blankrows: false
                                })[0]
                                newTypeName.push(typeName[0])
                            })
                            // console.log('newTypeName')
                            // console.log(newTypeName)
                            let newResults = []
                            rangeStringArray.map(rangeString => {
                                let result = XLSX.utils.sheet_to_json(worksheet, {
                                    range: rangeString,
                                    header: 1,
                                    blankrows: false,
                                    defval: ''
                                })
                                newResults.push(result)
                            })
                            // console.log(newResults)
                            const [...headers] = newResults[0][0]
                            headers.push('类别')
                            // console.log(headers)
                            const allResults = []
                            for (let i = 0; i < newResults.length; i++) {
                                for (let j = 1; j < newResults[i].length; j++) {
                                    let newItem = {
                                        order: 0,
                                        name: '',
                                        specification: '',
                                        unit: '',
                                        price: '',
                                        remark: '',
                                        category: ''
                                    }
                                    newItem.order = newResults[i][j][0]
                                    newItem.name = newResults[i][j][1]
                                    newItem.specification = newResults[i][j][2]
                                    newItem.unit = newResults[i][j][3]
                                    newItem.price = newResults[i][j][4]
                                    newItem.remark = newResults[i][j][5]
                                    newItem.category = newTypeName[i]
                                    allResults.push(newItem)
                                }
                            }
                            // console.log(allResults)
                            this.excelData.results = allResults
                            this.excelData.header = headers
                        } catch (e) {
                            // eslint-disable-next-line prefer-promise-reject-errors
                            return reject('解析excel文件出错，请核查excel内容的格式')
                        }
                        // this.generateData({ headers, allResults })
                        // console.log(this.excelData.results)
                        return resolve()
                    }
                    reader.readAsArrayBuffer(rawFile.raw)
                })
            },
            getRangeStringArray (worksheet) {
                const mergeArray = worksheet['!merges']
                const range = XLSX.utils.decode_range(worksheet['!ref'])
                // console.log(mergeArray)
                const rangeArray = []
                for (let i = 0; i < mergeArray.length; i++) {
                    let newRange = {
                        e: {
                            c: 0,
                            r: 0
                        },
                        s: {
                            c: 0,
                            r: 0
                        }
                    }
                    newRange.s.c = mergeArray[i].s.c
                    newRange.s.r = mergeArray[i].e.r + 1
                    newRange.e.c = mergeArray[i].e.c
                    if (i !== mergeArray.length - 1) {
                        newRange.e.r = mergeArray[i + 1].s.r - 1
                    } else {
                        newRange.e.r = range.e.r
                    }
                    rangeArray.push(newRange)
                }
                // console.log(rangeArray)
                const rangeStringArray = []
                rangeArray.map(newRange => {
                    let rangeString = XLSX.utils.encode_range(newRange)
                    rangeStringArray.push(rangeString)
                })
                // console.log(rangeStringArray)
                return rangeStringArray
            },
            isExcel (file) {
                return /\.(xlsx|xls)$/.test(file.name)
            },
            handleExceed (files, fileList) {
                // console.log(files)
                // console.log(fileList)
                this.showCloseableMessage('只能选择 1 个文件，请先删除已导入的文件', 'warning')
            },
            importExcel (excelFile) {
                this.loading = true
                if (!this.isExcel(excelFile)) {
                    this.showCloseableMessage('仅支持.xlsx, .xls后缀的文件', 'error')
                    return false
                }
                setData('lastImportFilePath', excelFile.raw.path)
                this.lastPath = excelFile.raw.path
                this.readerData(excelFile).then(() => {
                    this.loading = false
                }).catch(err => {
                    this.showCloseableMessage(err, 'error')
                    this.loading = false
                })
            },
            handleResetInput () {
                this.oldPassword = ''
                this.firstPassword = ''
                this.secondPassword = ''
            },
            handleChangePassword () {
                if (this.oldPassword === '' || this.firstPassword === '' || this.secondPassword === '') {
                    this.showCloseableMessage('密码不能为空', 'error')
                    return
                }
                if (this.oldPassword !== getData('password')) {
                    this.showCloseableMessage('原密码不正确', 'error')
                    return
                }
                if (this.firstPassword !== this.secondPassword) {
                    this.showCloseableMessage('两次输入的密码不一致', 'error')
                    return
                }
                setData('password', this.secondPassword)
                this.showCloseableMessage('修改密码成功', 'success')
                this.handleResetInput()
            },
            handleImportDB () {
                if (this.excelData.results === null || this.excelData.results.length === 0) {
                    this.showCloseableMessage('未读取到数据，请重新导入文件', 'error')
                    return
                }
                // console.log(this.excelData.results)
                this.loading = true
                try {
                    addItems(this.excelData.results)
                    this.resetData()
                    this.loading = false
                    this.showCloseableMessage('导入成功', 'success')
                } catch (e) {
                    this.showCloseableMessage('导入失败，请检查文件内容格式', 'error')
                    this.showCloseableMessage(e, 'error')
                    this.loading = false
                    this.resetData()
                }
            },
            handleBugReport () {
                let messageNum = this.createRandom()
                let positionNum = this.createRandom()
                let typeNum = this.createRandom()
                this.$notify({
                    title: '夏子猫',
                    type: this.typePool[typeNum],
                    message: this.bugMessagePool[messageNum],
                    position: this.positionPool[positionNum]
                })
            },
            createRandom () {
                return Math.floor(Math.random() * 4)
            },
            handleClearDB () {
                this.$confirm('此操作将清除数据库中的数据,但是不会影响导入的文件，是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.clearDBLoading = true
                    try {
                        clearItems()
                        this.clearDBLoading = false
                        this.showCloseableMessage('清除成功', 'success')
                    } catch (e) {
                        this.clearDBLoading = false
                        this.showCloseableMessage('操作失败', 'error')
                    }
                }).catch(() => {
                    this.showCloseableMessage('已取消', 'info')
                })
            },
            showCloseableMessage (msg, type) {
                this.$message({
                    showClose: true,
                    message: msg,
                    type: type,
                    duration: 2000
                })
            }
        },
        computed: {},
        mounted () {
            this.lastPath = getData('lastImportFilePath') || ''
            this.dbPath = getDBPath()
            // console.log(this.dbPath)
        }
    }
</script>

<style scoped>
  >>> .el-divider__text {
    background-color: #f0f8ff;
    font-size: 16px;
  }

  .file-path-container {
    display: block;
    align-items: center;
    width: 80%;
    margin: 0 auto;
  }

  .change-container {
    width: 28%;
    margin: 0 auto;
  }

  .change-container .el-input {
    margin: 0 0 5px 0;
  }

  .submit-container {
    display: flex;
    justify-content: space-between;
    margin-top: 5px;
  }

  >>> .el-upload__tip {
    margin-top: 0;
  }

  .init-db-container {
  }
 >>> .el-divider--horizontal {
    margin: 11px 0;
  }
  /*>>> .el-button--primary{*/
  /*  color: #fff;*/
  /*  background-color: #1758AF;*/
  /*  border-color: #1758AF;*/
  /*}*/
</style>
